# 导入所需的库
from poplib import POP3_SSL
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr

def decode_str(s):
    """解码字符串"""
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value

def get_email_content(msg):
    """获取邮件内容"""
    if msg.is_multipart():
        # 如果邮件包含多个部分，递归处理
        parts = []
        for part in msg.walk():
            if not part.is_multipart():
                content_type = part.get_content_type()
                if content_type == 'text/plain' or content_type == 'text/html':
                    content = part.get_payload(decode=True).decode(part.get_content_charset('utf-8'))
                    parts.append(content)
        return '\n'.join(parts)
    else:
        # 邮件只包含一个部分
        content_type = msg.get_content_type()
        if content_type == 'text/plain' or content_type == 'text/html':
            content = msg.get_payload(decode=True).decode(msg.get_content_charset('utf-8'))
            return content

def receive_email():
    # 邮箱服务器地址（例如：pop.gmail.com）
    pop3_server = 'XXX'
    
    # 邮箱账号和密码
    email = 'XXX@XXX.com'
    password = 'XXX'  # 可能需要使用应用专用密码
    
    try:
        # 连接到POP3服务器
        server = POP3_SSL(pop3_server)
        # 身份认证
        server.user(email)
        server.pass_(password)
        
        # 获取邮件数量和占用空间
        print(f'邮件数量: {server.stat()[0]}')
        
        # 获取最新的5封邮件
        num_emails = min(5, len(server.list()[1]))
        
        for i in range(num_emails):
            # 邮件号码从1开始
            email_index = len(server.list()[1]) - i
            
            # 获取邮件
            lines = server.retr(email_index)[1]
            
            # 解析邮件内容
            msg_content = b'\r\n'.join(lines).decode('utf-8')
            msg = Parser().parsestr(msg_content)
            
            # 获取发件人、主题
            from_addr = parseaddr(msg.get('From'))[1]
            subject = decode_str(msg.get('Subject', ''))
            
            print(f'\n邮件 {i+1}:')
            print(f'发件人: {from_addr}')
            print(f'主题: {subject}')
            print('内容预览:')
            content = get_email_content(msg)
            print(content[:200] + '...' if len(content) > 200 else content)
        
        # 关闭连接
        server.quit()
        
    except Exception as e:
        print(f'发生错误: {str(e)}')

if __name__ == '__main__':
    receive_email()
